<?php
namespace Dao;

class Queue {
    protected static $function = array('pop', 'push', 'len');

    protected $pool_type = '';
    protected $pool_name = '';

    protected $key = array();
    protected function setConfig($name, $key){
        $name = strtolower($name);
        $this->$name = array(
            'key'   => $key,
        );
    }

    public function __call($name, $arguments) {
        $function = null;
        foreach(self::$function as $need_function){
            if(stripos($name, $need_function) === 0){
                $function = $need_function;
            }
        }
        if(!$function){
            throw new \Exception("this class no $function, only pop push len");
        }

        $name = strtolower(substr($name, strlen($function)));
        if(!isset($this->$name) || empty($this->$name)){
            throw new \Exception("$name is not setConfig");
        }
        if(!$this->pool_name || !$this->pool_type){
            throw new \Exception("class need set pool_name and pool_type");
        }

        $pool = \S\Queue\Queue::pool($this->pool_type, $this->pool_name);
        $config = $this->$name;
        if($function == "pop") {
            $ret = $pool->pop($config['key']);
            if($ret){
                $ret = json_decode($ret, true);
            }else{
                $ret = array();
            }
        }elseif($function == "push"){
            $ret = $pool->push($config['key'], json_encode($arguments[0]))?true:false;
        }else{
            $ret = $pool->len($config['key']);
        }
        return $ret;
    }
}